package com.example.yunhailutong.zhongtan.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.yunhailutong.zhongtan.Adapter.SecondPartViewPagerAdapter;
import com.example.yunhailutong.zhongtan.Adapter.ThirdPartViewPagerAdapter;
import com.example.yunhailutong.zhongtan.R;
import com.example.yunhailutong.zhongtan.app.OldsEvent;
import com.example.yunhailutong.zhongtan.entity.HomeEntity;
import com.example.yunhailutong.zhongtan.entity.HomeEntity.DataBean.HomeInfoBean;
import com.example.yunhailutong.zhongtan.entity.HomeEntity.DataBean.LstBannerBean;
import com.example.yunhailutong.zhongtan.net.PersionBiz;
import com.example.yunhailutong.zhongtan.weight.PopWindow;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * A simple {@link Fragment} subclass.
 */
public class MainFragment extends BaseFragment {
    Unbinder unbinder;
    @BindView(R.id.message)
    ImageView message;

    //init Banner
    @BindView(R.id.banner)
    Banner banner;
    private View view;

    //init second part
    @BindView(R.id.second_part_view_pager)
    ViewPager mSecondPartViewPager;
    private SecondPartViewPagerAdapter mSecondPartViewPagerAdapter;

    //init third part
    @BindView(R.id.magicindicator2)
    MagicIndicator magicIndicator2;
    @BindView(R.id.third_part_view_pager)
    ViewPager mThirdPartViewPager;
    private static final String[] THIRD_VIEW_PAGER_CHANNELS = new String[]{"黛溪风采", "法律援助", "社区头条", "曝光台"};
    private List<String> mThirdPartViewPagerData = Arrays.asList(THIRD_VIEW_PAGER_CHANNELS);
    private ThirdPartViewPagerAdapter mThirdPartViewPagerAdapter;

    private List<LstBannerBean> lstBannerBeans;
    private List<HomeInfoBean> lstDjxcBeans;


    public MainFragment() {
        // Required empty public constructor
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        new PersionBiz().getHome();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.fragment_main, container, false);
        unbinder = ButterKnife.bind(this, view);

        message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(v.getId() == R.id.message) {
                    PopWindow popWindow = new PopWindow(v.getContext());
                    popWindow.showPopupWindow(v.findViewById(R.id.message));
                }
            }
        });

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        new PersionBiz().getHome();
    }

    private void updateView(final HomeEntity homeEntity) {
        lstBannerBeans = homeEntity.getData().getLstBanner();
        mSecondPartViewPagerAdapter = new SecondPartViewPagerAdapter(homeEntity.getData());
        mThirdPartViewPagerAdapter = new ThirdPartViewPagerAdapter(homeEntity.getData());
        initBanner(lstBannerBeans);
        initSecondPart();
        initThirdPart();
    }
    private void initBanner(List<LstBannerBean> lstBannerBeans) {
        ArrayList<String> list_path = new ArrayList<>();
        for (LstBannerBean lstBannerBean : lstBannerBeans) {
            if (lstBannerBean.getIm_imgPath() != null && !lstBannerBean.getIm_imgPath().isEmpty()) {
                list_path.add(lstBannerBean.getIm_imgPath());
            }
        }
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setImageLoader(new MyBannerImageLoader());
        banner.setBannerAnimation(Transformer.Default);
        banner.setImages(list_path);
        banner.setDelayTime(3000);
        banner.isAutoPlay(true);
        //暂时不需要
        banner.setIndicatorGravity(BannerConfig.CENTER).setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        }).start();
    }

    private void initSecondPart() {
        mSecondPartViewPager.setAdapter(mSecondPartViewPagerAdapter);
    }

    private void initThirdPart() {
        mThirdPartViewPager.setAdapter(mThirdPartViewPagerAdapter);
        initMagicIndicator2();
    }

    private void initMagicIndicator2() {
        magicIndicator2.setBackgroundColor(Color.WHITE);
                CommonNavigator commonNavigator = new CommonNavigator(getContext());
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mThirdPartViewPagerData.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, int i) {
                final int index = i;
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);
                View view = LayoutInflater.from(context).inflate(R.layout.fragment_main_third_part_title, null);
                final TextView titleText = view.findViewById(R.id.third_part_text_view);
                titleText.setText(mThirdPartViewPagerData.get(index));
                commonPagerTitleView.setContentView(view);
                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {
                    @Override
                    public void onSelected(int i, int i1) {
                        titleText.setTextColor(Color.BLACK);
                        titleText.setBackgroundResource(R.drawable.background_third_part_textview_2);
                    }

                    @Override
                    public void onDeselected(int i, int i1) {
                        titleText.setTextColor(Color.BLACK);
                        titleText.setBackgroundResource(R.drawable.background_third_part_textview_1);
                    }

                    @Override
                    public void onLeave(int i, int i1, float v, boolean b) {
                        //titleText.setScaleX(1.0f + (0.9f - 1.0f)*v);
                        //titleText.setScaleY(1.0f + (0.9f - 1.0f)*v);
                    }

                    @Override
                    public void onEnter(int i, int i1, float v, boolean b) {
                        //titleText.setScaleX(1.0f + (1.0f - 0.9f)*v);
                        //titleText.setScaleY(1.0f + (1.0f - 0.9f)*v);
                    }
                });
                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mThirdPartViewPager.setCurrentItem(index);
                    }
                });
                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        });
        magicIndicator2.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator2, mThirdPartViewPager);
    }

    private void initMagicIndicator1() {
//        ScaleCircleNavigator scaleCircleNavigator = new ScaleCircleNavigator(getContext());
//        scaleCircleNavigator.setCircleCount(3);
//        scaleCircleNavigator.setNormalCircleColor(Color.LTGRAY);
//        scaleCircleNavigator.setSelectedCircleColor(Color.DKGRAY);
//        scaleCircleNavigator.setCircleClickListener(new ScaleCircleNavigator.OnCircleClickListener() {
//            @Override
//            public void onClick(int index) {
//                mSecondPartViewPager.setCurrentItem(index);
//            }
//        });
//        magicIndicator1.setNavigator(scaleCircleNavigator);
//        ViewPagerHelper.bind(magicIndicator1, mSecondPartViewPager);
    }

    private class MyBannerImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context).load((String)path).into(imageView);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onClick(View v) {

    }


    @Subscribe
    public void log(final OldsEvent.HomeEvent msg) {
        if (msg.what == -1) {
            disPlay(msg.obj.toString());
        } else if (msg.what == 1) {
            updateView((HomeEntity) msg.obj);
        }

    }

    @Subscribe
    public void IsHaveMessageEvent(OldsEvent.IsHaveMessageEvent msg) {
//        if (msg.what == -1) {
//            fabugongying.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    disPlay("尚未完善个人资料，请完善个人资料后重试");
//                }
//            });
//            fabuxuqiu.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    disPlay("尚未完善个人资料，请完善个人资料后重试");
//                }
//            });
//        }
//        if (msg.what == 1) {
//            fabugongying.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent(getActivity(), ActivityNewGongYing.class);
//                    intent.putExtra("type", "1");
//
//                    startActivity(intent);
//                }
//            });
//            fabuxuqiu.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//
//
//                    Intent intent = new Intent(getActivity(), ActivityNewGongYing.class);
//                    intent.putExtra("type", "2");
//                    startActivity(intent);
//                }
//            });
//        }
    }

//        @Override
//        protected void convert(BaseViewHolder helper, HomeEntity.DataBean.FactoryBean item) {
//            System.out.print("这是" + item);
//            if (item.getLogo().equals("")) {
//                // Picasso.with(mContext).load("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3094121875,3546519224&fm=27&gp=0.jpg").into((ImageView) helper.getView(R.id.image));
//
//            } else {
//                Picasso.with(mContext).load(item.getLogo()).into((ImageView) helper.getView(R.id.image));
//                //Picasso.with(mContext).load("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3094121875,3546519224&fm=27&gp=0.jpg").into((ImageView) helper.getView(R.id.image));
//
//            }
//        }

//
//    public class gongyingAdapter extends BaseQuickAdapter<HomeEntity.DataBean.SupplyBean, BaseViewHolder> {
//        public gongyingAdapter(int layoutResId, List data) {
//            super(layoutResId, data);
//        }
//
//
//        @Override
//        protected void convert(BaseViewHolder helper, HomeEntity.DataBean.SupplyBean item) {
//            System.out.print("这是" + item);
//            if (item.getImg().equals("")) {
//                //  Picasso.with(mContext).load("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3094121875,3546519224&fm=27&gp=0.jpg").into((ImageView) helper.getView(R.id.image));
//            } else {
//                String image = item.getImg();
//                String encode = null;
//                try {
//                    encode = URLEncoder.encode(image, "UTF-8");
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//                String replace = encode.replace("%3A", ":").replace("%2F", "/");
//                Picasso.with(mContext).load(replace).into((ImageView) helper.getView(R.id.image));
//                //Picasso.with(mContext).load("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3094121875,3546519224&fm=27&gp=0.jpg").into((ImageView) helper.getView(R.id.image));
//            }
//            helper.setText(R.id.title, item.getTitle());
//            helper.setText(R.id.cost, item.getPrice());
//            helper.setText(R.id.nums, item.getNum() + "吨");
//        }
//    }
//
//    public class xuqiuAdapter extends BaseQuickAdapter<HomeEntity.DataBean.DemandBean, BaseViewHolder> {
//        public xuqiuAdapter(int layoutResId, List data) {
//            super(layoutResId, data);
//        }
//
//
//        @Override
//        protected void convert(BaseViewHolder helper, HomeEntity.DataBean.DemandBean item) {
//            System.out.print("这是" + item);
//            if (item.getImg().equals("")) {
//                //Picasso.with(mContext).load("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3094121875,3546519224&fm=27&gp=0.jpg").into((ImageView) helper.getView(R.id.image));
//
//            } else {
//                String image = item.getImg();
//                String encode = null;
//                try {
//                    encode = URLEncoder.encode(image, "UTF-8");
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//                String replace = encode.replace("%3A", ":").replace("%2F", "/");
//                Picasso.with(mContext).load(replace).into((ImageView) helper.getView(R.id.image));
//                //Picasso.with(mContext).load("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3094121875,3546519224&fm=27&gp=0.jpg").into((ImageView) helper.getView(R.id.image));
//            }
//            helper.setText(R.id.title, item.getTitle());
//            helper.setText(R.id.cost, item.getPrice());
//            helper.setText(R.id.nums, item.getNum() + "吨");
//        }
//    }
}
